//
//  ExGradientView.m
//  OC-Example
//
//  Created by apang on 2018/7/31.
//  Copyright © 2018年 apang.men All rights reserved.
//

#import "ExGradientView.h"

#define   DEGREES(degrees)  ((M_PI * (degrees))/ 180.f)
@interface ExGradientView()<CAAnimationDelegate>
@property (strong ,nonatomic) UIBezierPath * dashedPath;
@property (strong, nonatomic) CAShapeLayer * dashedLayer;
//@property (strong, nonatomic) CAGradientLayer * gradientLayer;
//@property (strong, nonatomic) CALayer * gradientBackLayer;
@property (strong, nonatomic) NSMutableArray * gradientColors;
@property (assign, nonatomic) float progress;
@end
@implementation ExGradientView
@synthesize animating;
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        CAGradientLayer *layer = (id)[self layer];
        [layer setStartPoint:CGPointMake(0.0, 0.5)];
        [layer setEndPoint:CGPointMake(1.0, 0.5)];

        _gradientColors = [NSMutableArray array];
        for (NSInteger deg = 0; deg <= 360; deg += 5) {

            UIColor *color;
            color = [UIColor colorWithHue:1.0 * deg / 360.0
                               saturation:1.0
                               brightness:1.0
                                    alpha:1.0];
            [_gradientColors addObject:(id)[color CGColor]];
        }

        [layer setColors:_gradientColors];



        _dashedPath = [UIBezierPath bezierPath];
        [_dashedPath moveToPoint:CGPointMake(10, 10)];
        [_dashedPath addLineToPoint:CGPointMake(CGRectGetWidth(frame)-20.0, 10)];
        [_dashedPath addLineToPoint:CGPointMake(CGRectGetWidth(frame)-20.0, CGRectGetHeight(frame)-20.0)];
        //        [_dashedPath addLineToPoint:CGPointMake(10, CGRectGetHeight(frame)-20.0)];
        //        [_dashedPath closePath];

        _dashedLayer = [CAShapeLayer layer];
        _dashedLayer.path = _dashedPath.CGPath;
        _dashedLayer.strokeColor = [UIColor colorWithWhite:0.4235 alpha:1.0].CGColor;
        _dashedLayer.fillColor = [[UIColor clearColor] CGColor];
        _dashedLayer.lineWidth = 0.8;
        _dashedLayer.frame = CGRectMake(0, 0, CGRectGetWidth(frame), CGRectGetHeight(frame));
        _dashedLayer.lineDashPattern = @[@4, @2];
        _dashedLayer.lineCap = kCALineCapRound;
        _dashedLayer.lineJoin = kCALineCapRound;
        //        _dashedLayer.strokeEnd = 0;
        [layer setMask:_dashedLayer];
        _progress = 0.0;
    }
    return self;
}
+(Class)layerClass{
    return [CAGradientLayer class];
}
-(void)layoutSubviews{
    [super layoutSubviews];
    CGRect maskRect = [_dashedLayer frame];
    maskRect.size.width = CGRectGetWidth([self bounds]);
    [_dashedLayer setFrame:maskRect];
}
-(NSArray *)shitColorsWith:(NSArray *)colors{
    NSMutableArray * tmpColors = [colors mutableCopy];
    id last = [tmpColors lastObject];
    [tmpColors removeLastObject];
    [tmpColors insertObject:last atIndex:0];
    return tmpColors;
}
-(void)animationMethod{

    CAGradientLayer *layer = (id)[self layer];
    NSArray *fromColors = [layer colors];
    NSArray *toColors = [self shitColorsWith:fromColors];
    [layer setColors:toColors];

    CABasicAnimation *animation;
    animation = [CABasicAnimation animationWithKeyPath:@"colors"];
    [animation setFromValue:fromColors];
    [animation setToValue:toColors];
    [animation setDuration:0.08];
    [animation setRemovedOnCompletion:YES];
    [animation setFillMode:kCAFillModeForwards];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
    [animation setDelegate:self];

    // Add the animation to our layer

    [layer addAnimation:animation forKey:@"animateGradient"];

    if (_progress==100.0) {
        _progress = 0.0;
    }
    _progress +=1.0;
    //    _dashedLayer.strokeEnd = _progress/100.0;
}
- (void)animationDidStop:(CAAnimation *)animation finished:(BOOL)flag {

    if ([self isAnimating]) {

        [self animationMethod];
    }
}
-(void)startAnimating{
    if (![self isAnimating]) {
        animating = YES;
        [self animationMethod];
    }
}
-(void)stopAnimating{
    if ([self isAnimating]) {
        animating = NO;
    }
}
@end


@interface ExLineGradientView()<CAAnimationDelegate>
@property (strong, nonatomic) CALayer * maskLayer;
@end

@implementation ExLineGradientView
@synthesize animating;
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        CAGradientLayer *layer = (id)[self layer];
        [layer setStartPoint:CGPointMake(0.0, 0.5)];
        [layer setEndPoint:CGPointMake(1.0, 0.5)];

        // Create the gradient colors using hues in 5 degree increments

        NSMutableArray *colors = [NSMutableArray array];
        for (NSInteger deg = 0; deg <= 360; deg += 5) {

            UIColor *color;
            color = [UIColor colorWithHue:1.0 * deg / 360.0
                               saturation:1.0
                               brightness:1.0
                                    alpha:1.0];
            [colors addObject:(id)[color CGColor]];
        }
        [layer setColors:[NSArray arrayWithArray:colors]];

        // Create another layer to use as a mask. The width of this layer will
        // be modified to reflect the current progress value.

        _maskLayer = [CALayer layer];
        [_maskLayer setFrame:CGRectMake(0, 0, 0, frame.size.height)];
        [_maskLayer setBackgroundColor:[[UIColor blackColor] CGColor]];
        [layer setMask:_maskLayer];
    }
    return self;
}
+ (Class)layerClass {

    // Tells UIView to use CAGradientLayer as our backing layer

    return [CAGradientLayer class];
}
-(void)layoutSubviews{
    [super layoutSubviews];
    CGRect maskRect = [_maskLayer frame];
    maskRect.size.width = CGRectGetWidth([self bounds]);
    [_maskLayer setFrame:maskRect];

}
-(NSArray *)shitColorsWith:(NSArray *)colors{
    NSMutableArray * tmpColors = [colors mutableCopy];
    id last = [tmpColors lastObject];
    [tmpColors removeLastObject];
    [tmpColors insertObject:last atIndex:0];
    return tmpColors;
}
-(void)animationMethod{
    CAGradientLayer *layer = (id)[self layer];
    NSArray *fromColors = [layer colors];
    NSArray *toColors = [self shitColorsWith:fromColors];
    [layer setColors:toColors];

    CABasicAnimation *animation;
    animation = [CABasicAnimation animationWithKeyPath:@"colors"];
    [animation setFromValue:fromColors];
    [animation setToValue:toColors];
    [animation setDuration:0.08];
    [animation setRemovedOnCompletion:YES];
    [animation setFillMode:kCAFillModeForwards];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
    [animation setDelegate:self];
    [layer addAnimation:animation forKey:@"animateGradient"];
}
- (void)animationDidStop:(CAAnimation *)animation finished:(BOOL)flag {

    if ([self isAnimating]) {

        [self animationMethod];
    }
}
-(void)startAnimating{
    if (![self isAnimating]) {
        animating = YES;
        [self animationMethod];
    }
}
-(void)stopAnimating{
    if ([self isAnimating]) {
        animating = NO;
    }
}
@end

@interface ExDashLineGradientView ()
@property (strong, nonatomic) CAShapeLayer * dashedLayer;
@end

@implementation ExDashLineGradientView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        CAGradientLayer *layer = (id)[self layer];
        [layer setStartPoint:CGPointMake(0.0, 0.5)];
        [layer setEndPoint:CGPointMake(1.0, 0.5)];

        // Create the gradient colors using hues in 5 degree increments

        NSMutableArray *colors = [NSMutableArray array];
        for (NSInteger deg = 0; deg <= 360; deg += 5) {

            UIColor *color;
            color = [UIColor colorWithHue:1.0 * deg / 360.0
                               saturation:1.0
                               brightness:1.0
                                    alpha:1.0];
            [colors addObject:(id)[color CGColor]];
        }
        [layer setColors:[NSArray arrayWithArray:colors]];

        UIBezierPath * dashedPath = [UIBezierPath bezierPath];
        [dashedPath moveToPoint:CGPointZero];
        [dashedPath addLineToPoint:CGPointMake(CGRectGetWidth(frame), CGRectGetHeight(frame))];
        //        [dashedPath addLineToPoint:CGPointMake(CGRectGetWidth(frame)-20.0, CGRectGetHeight(frame)-20.0)];
        //        [_dashedPath closePath];

        _dashedLayer = [CAShapeLayer layer];
        _dashedLayer.path = dashedPath.CGPath;
        _dashedLayer.strokeColor = [UIColor colorWithWhite:0.4235 alpha:1.0].CGColor;
        _dashedLayer.fillColor = [[UIColor clearColor] CGColor];
        _dashedLayer.lineWidth = 1.0;
        _dashedLayer.frame = CGRectMake(0, 0, CGRectGetWidth(frame), CGRectGetHeight(frame));
        _dashedLayer.lineDashPattern = @[@4, @10];//4=线的宽度 10=每条线的间距
        _dashedLayer.lineCap = kCALineCapRound;
        _dashedLayer.lineJoin = kCALineCapRound;
        [layer setMask:_dashedLayer];
    }
    return self;
}
-(void)layoutSubviews{
    [super layoutSubviews];
    CGRect maskRect = [_dashedLayer frame];
    maskRect.size.width = CGRectGetWidth([self bounds]);
    [_dashedLayer setFrame:maskRect];
}
@end


@interface ExDashCircleGradientView ()
@property (strong, nonatomic) CAShapeLayer * dashedLayer;
@property (assign, nonatomic) float  progress;
@end

@implementation ExDashCircleGradientView

-(instancetype)initWithFrame:(CGRect)frame{

    self = [super initWithFrame:frame];
    if (self) {
        CAGradientLayer *layer = (id)[self layer];
        [layer setStartPoint:CGPointMake(0.0, 0.5)];
        [layer setEndPoint:CGPointMake(1.0, 0.5)];

        // Create the gradient colors using hues in 5 degree increments
        layer.position = self.center;
        NSMutableArray *colors = [NSMutableArray array];
        for (NSInteger deg = 0; deg <= 360; deg += 5) {

            UIColor *color;
            color = [UIColor colorWithHue:1.0 * deg / 360.0
                               saturation:1.0
                               brightness:1.0
                                    alpha:1.0];
            [colors addObject:(id)[color CGColor]];
        }
        [layer setColors:[NSArray arrayWithArray:colors]];

        UIBezierPath * dashedPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(CGRectGetWidth(frame)/2.0, CGRectGetHeight(frame)/2.0) radius:((CGRectGetWidth(frame)>CGRectGetHeight(frame)?:CGRectGetHeight(frame))/2.0-10.0) startAngle:DEGREES(0) endAngle:DEGREES(360) clockwise:YES];

        _dashedLayer = [CAShapeLayer layer];
        _dashedLayer.path = dashedPath.CGPath;
        _dashedLayer.strokeColor = [UIColor colorWithWhite:0.4235 alpha:1.0].CGColor;
        _dashedLayer.fillColor = [[UIColor clearColor] CGColor];
        _dashedLayer.lineWidth = 1.0;
        //        _dashedLayer.frame = CGRectMake(0, 0, CGRectGetWidth(frame), CGRectGetHeight(frame));
        _dashedLayer.lineDashPattern = @[@10, @4];//10=线的宽度 4=每条线的间距
        //        _dashedLayer.lineCap = kCALineCapRound;
        //        _dashedLayer.lineJoin = kCALineCapRound;
        _dashedLayer.strokeEnd = 1.0f;
        _dashedLayer.strokeStart = 0.0f;
        [layer setMask:_dashedLayer];
        _progress = 0.0;
    }
    return self;
}
-(void)animationMethod{
    [super animationMethod];
    if (_progress > 100) {
        _progress = 0;
    }
    //    _dashedLayer.strokeEnd = _progress/100.0;
    //    _progress++;

}
-(void)layoutSubviews{
    [super layoutSubviews];
    CGRect maskRect = [_dashedLayer frame];
    maskRect.size.width = CGRectGetWidth([self bounds]);
    [_dashedLayer setFrame:maskRect];
}
@end

//http://www.cnblogs.com/liyang31tg/p/4151288.html
// 将常数转换为度数

@interface CircleGredient()
@property (nonatomic, strong) CAGradientLayer *colorLayer;
@property (nonatomic, strong) NSTimer * timer;
@end
@implementation CircleGredient
@synthesize colorLayer,animating;
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        //        [self setBackgroundColor:[UIColor cyanColor]];

        colorLayer = [CAGradientLayer layer];
        colorLayer.backgroundColor = [UIColor blueColor].CGColor;
        colorLayer.frame    = (CGRect){CGPointZero, CGSizeMake(CGRectGetWidth(frame), CGRectGetHeight(frame))};
        //        colorLayer.position = self.center;
        [self.layer addSublayer:colorLayer];

        // 颜色分配
        colorLayer.colors = @[(__bridge id)[UIColor redColor].CGColor,
                              (__bridge id)[UIColor whiteColor].CGColor,
                              (__bridge id)[UIColor redColor].CGColor];
        colorLayer.locations  = @[@(-0.2), @(-0.1), @(0)];

        // 起始点
        colorLayer.startPoint = CGPointMake(0, 0);

        // 结束点
        colorLayer.endPoint   = CGPointMake(1, 0);

        CAShapeLayer *circle = [CircleGredient LayerWithCircleCenter:CGPointMake(CGRectGetWidth(frame)/2.0, CGRectGetWidth(frame)/2.0)
                                                              radius:CGRectGetWidth(frame)/2.0-10.0
                                                          startAngle:DEGREES(0)
                                                            endAngle:DEGREES(360)
                                                           clockwise:YES
                                                     lineDashPattern:nil];
        circle.strokeColor = [UIColor redColor].CGColor;
        [self.layer addSublayer:circle];
        circle.strokeEnd = 1.f;
        colorLayer.mask = circle;
        _timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(testEvent) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];

    }
    return self;
}
-(void)startAnimating{
    if (![self isAnimating]) {
        animating = YES;
        [_timer fire];
    }
}
-(void)stopAnimating{
    if ([self isAnimating]) {
        animating = NO;
        [_timer invalidate];
    }
}
-(void)testEvent{
    static int i = 0;
    if (i++ % 2 == 0)
    {
        CABasicAnimation* fadeAnim = [CABasicAnimation animationWithKeyPath:@"locations"];
        fadeAnim.fromValue = @[@(-0.2), @(-0.1), @(0)];
        fadeAnim.toValue   = @[@(1.0), @(1.1), @(1.2)];
        fadeAnim.duration  = 1.5;
        [colorLayer addAnimation:fadeAnim forKey:nil];
    }
}
+ (CAShapeLayer *)LayerWithCircleCenter:(CGPoint)point
                                 radius:(CGFloat)radius
                             startAngle:(CGFloat)startAngle
                               endAngle:(CGFloat)endAngle
                              clockwise:(BOOL)clockwise
                        lineDashPattern:(NSArray *)lineDashPattern
{
    CAShapeLayer *layer = [CAShapeLayer layer];

    // 贝塞尔曲线(创建一个圆)
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:point
                                                        radius:radius
                                                    startAngle:startAngle
                                                      endAngle:endAngle
                                                     clockwise:clockwise];
    
    // 获取path
    layer.path = path.CGPath;
    //    layer.position = CGPointMake(0, 0);
    
    
    // 设置填充颜色为透明
    layer.fillColor = [UIColor clearColor].CGColor;
    
    // 获取曲线分段的方式
    if (lineDashPattern)
    {
        layer.lineDashPattern = lineDashPattern;
    }
    
    return layer;
}
@end
